package thread;

public class MultiThreadShareData {

	// private static ShareData data1 = new ShareData();

	public static void main(String[] args) {
		/*方法a)*/
		/*ShareData data2 = new ShareData();
		new Thread(new MyRunnable1(data2)).start();
		new Thread(new MyRunnable2(data2)).start();*/

		/*方法b)*/
		final ShareData data1 = new ShareData();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(2000L);
						data1.decrement();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000L);
						data1.increment();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}
		}).start();
	}
}
/*实现加处理*/
class MyRunnable1 implements Runnable {
	private ShareData data1;

	public MyRunnable1(ShareData data1) {
		this.data1 = data1;
	}

	public void run() {
		while (true) {
			try {
				Thread.sleep(2000L);
				data1.decrement();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}
}

/*实现减处理*/
class MyRunnable2 implements Runnable {
	private ShareData data1;

	public MyRunnable2(ShareData data1) {
		this.data1 = data1;
	}

	public void run() {
		while (true) {
			try {
				Thread.sleep(1000L);
				data1.increment();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class ShareData {
	private int j = 0;

	public synchronized void increment() {
		j++;
		System.out.println("J+1=" + j);
	}

	public synchronized void decrement() {
		j--;
		System.out.println("J-1=" + j);
	}
}
